package appController

import (
	"CMETO/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

// app部分的接口
type GoodsTypeController struct{}

// @Summary 商品分类查询（树状所有）
// @Description 树状查询商品分类
// @Tags APP管理
// @Accept json
// @Produce json
// @param name query string false "商品分类名"
// @Success 200 {object} models.ResultCommon[[]models.GoodsType] "查询成功"
// @Success 401 {object} models.ResultCommon[string] "查询失败"
// @Router /app/goodsType [get]
// @Security JWT
func (r GoodsTypeController) QueryGoodsTypes(ctx *gin.Context) {
	nameStr := ctx.DefaultQuery("name", "")
	name := "%" + nameStr + "%"
	var goodsType []models.GoodsType
	err := models.DB.Preload("Children", "is_delete=0 AND status = 1 AND name like ?", name).Preload("Children.Children", "is_delete=0 AND status = 1 AND name like ?", name).Where("fid=0 AND is_delete=0 AND status=1 AND name like ?", name).Find(&goodsType).Error
	for i, t := range goodsType {
		for j, k := range t.Children {
			goodsList := []models.Goods{}
			models.DB.Where("sid = ? AND is_delete=0 AND status=1", k.Id).Find(&goodsList)
			goodsType[i].Children[j].GoodsList = goodsList
		}
	}
	if err != nil {
		ctx.JSON(http.StatusOK, models.ResultCommon[string]{
			Msg:    "查询失败",
			Code:   "400",
			Result: "",
		})
	} else {
		ctx.JSON(http.StatusOK, models.ResultCommon[[]models.GoodsType]{
			Msg:    "查询成功",
			Code:   "200",
			Result: goodsType,
		})
	}
}
